/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.hb.BusinessPartnerDAOImpl;
import com.wii.elpro.dao.hb.CabangDAOImpl;
import com.wii.elpro.dao.hb.FinishingDAOImpl;
import com.wii.elpro.dao.hb.InqueryDAOImpl;
import com.wii.elpro.dao.hb.ProductSpecificationImpl;
import com.wii.elpro.dao.hb.ProjectDAOImpl;
import com.wii.elpro.dao.hb.QuotationDAOImpl;
import com.wii.elpro.dao.hb.StandartSpecificationImpl;
import com.wii.elpro.dao.hb.UserDAOImpl;
import com.wii.elpro.entity.BusinessPartner;
import com.wii.elpro.entity.Cabang;
import com.wii.elpro.entity.Finishing;
import com.wii.elpro.entity.Inquery;
import com.wii.elpro.entity.ProductSpecification;
import com.wii.elpro.entity.Project;
import com.wii.elpro.entity.Quotation;
import com.wii.elpro.entity.StandartSpecification;
import com.wii.elpro.entity.User;
import com.wii.elpro.web.form.InquiryNewForm;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author JollkY
 */
public class InquiryPreSaveAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User users = (User)sess.getAttribute("userSession");    
        InqueryDAOImpl dao = new InqueryDAOImpl();
        if(users==null){
            return mapping.findForward("gagalLogin");            
        }  
        String forward;
        ActionMessages messages = null;
       
        InquiryNewForm f = (InquiryNewForm) form;
        User s = null;
        if(sess.getAttribute("userSession")!=null) {
            s = (User) sess.getAttribute("userSession");
            s = new UserDAOImpl().getUser(s.getId());
        }
        try {
            List<User> sales = new ArrayList<User>();

            // MARKETING ONLY
            for(User user : new UserDAOImpl().getUsers()) {
                if(user.getDepartemen().getKode().equalsIgnoreCase("MRKT")) {
                    sales.add(user);
                }
            }
            List<Project> projects = new ProjectDAOImpl().getProjects();
            List<ProductSpecification> productSpecs = new ProductSpecificationImpl().getProductSpecifications();
            List<StandartSpecification> standardSpecs = new StandartSpecificationImpl().getStandartSpecifications();
            List<Finishing> finishings = new FinishingDAOImpl().getFinishings();
            List<BusinessPartner> contractors = new BusinessPartnerDAOImpl().getBusinessPartnersByLevel(3);
            List<BusinessPartner> consultants = new BusinessPartnerDAOImpl().getBusinessPartnersByLevel(4);
            List<Cabang> cabangs = new CabangDAOImpl().getCabangs();

            // SET TO REQUEST
            request.setAttribute("saless", sales);
            request.setAttribute("projects", projects);
            request.setAttribute("productSpecs", productSpecs);
            request.setAttribute("standardSpecs", standardSpecs);
            request.setAttribute("finishings", finishings);
            request.setAttribute("contactors", contractors);
            request.setAttribute("consultants", consultants);
            request.setAttribute("cabangs", cabangs);
            // ====== ENDS HERE ======
            
            if(sess.getAttribute("updateInquiry")==null) {
                // GENERATE QUOTATION NUMBER
                Calendar c = Calendar.getInstance();
                NumberFormat nf = NumberFormat.getNumberInstance();
                nf.setMinimumIntegerDigits(5);
                nf.setGroupingUsed(false);
                NumberFormat nf2 = NumberFormat.getNumberInstance();
                nf2.setMinimumIntegerDigits(2);
                nf2.setGroupingUsed(false);
                String quotationNumber = c.get(Calendar.YEAR)+"/"+nf2.format(c.get(Calendar.MONTH)+1)+"/"+s.getCabang().getKode()+"/";

                if(dao.getLastInquiry()!=null) {
                    Inquery inquiry = dao.getLastInquiry();
                    String tanggal = inquiry.getTanggal().toString();
                    String[] split = tanggal.split("-");
                    String year = split[0];
//                    System.out.println(c.get(Calendar.YEAR));
//                    System.out.println(year);
                    if(c.get(Calendar.YEAR)==Integer.parseInt(year)) {
                        String lastQuotationNumber = inquiry.getNoQuotation();
                        split = lastQuotationNumber.split("/");
                        quotationNumber = quotationNumber+nf.format(nf.parse(split[3]).intValue()+1);
//                        System.out.println("1");
                    } else {
                        quotationNumber = quotationNumber+nf.format(1);
//                        System.out.println("2");
                    }                
                } else {
                    quotationNumber = quotationNumber+nf.format(1);
//                    System.out.println("3");
                }

                f.setNoQuotation(quotationNumber);
                f.setSales(s.getId());
            } 
            // Jika inquiry merupkan revisi quotation
            else {
                long idQuotation = (Long) sess.getAttribute("updateInquiry");
                sess.removeAttribute("updateInquiry");
                Quotation quotation = new QuotationDAOImpl().getQuotation(idQuotation);
                f.setNoQuotation(quotation.getSpdcf().getInquery().getNoQuotation());
                f.setSales(quotation.getSpdcf().getInquery().getSales().getId());
                f.setProject(quotation.getSpdcf().getInquery().getProject().getId());
                f.setAlamat(quotation.getSpdcf().getInquery().getAlamat());
                f.setCabang(quotation.getSpdcf().getInquery().getCabang().getId());
                f.setFinishing(quotation.getSpdcf().getInquery().getFinishing().getId());
                f.setKonsultan(quotation.getSpdcf().getInquery().getKonsultan().getId());
                f.setKontraktor(quotation.getSpdcf().getInquery().getKontraktor().getId());
                f.setProductSpec(quotation.getSpdcf().getInquery().getProductSpec().getId());
                f.setStandartSpec(quotation.getSpdcf().getInquery().getStandartSpec().getId());                
            }
            forward = "success";
        } catch (Exception ex) {
            messages = new ActionMessages();
            messages.add("message", new ActionMessage("customMessage", "Application is fail to retrieve data. Please contact my developer."));
            saveMessages(sess, messages);
            ex.printStackTrace();
            forward = "fail";
        }
        return mapping.findForward(forward);
    }
}
